//
//  HMMainTabar.swift
//  HMWeibo12
//
//  Created by 陈伯共 on 16/9/17.
//  Copyright © 2016年 陈伯共. All rights reserved.
//

import UIKit

class HMMainTabar: UITabBar {
    //加号按钮的闭包属性
    var composeCallback:(() -> Void)?
    
    //按钮的数量
    let count = 5
    
    //懒加载加号按钮
    lazy var composeButton: UIButton = {
        let button = UIButton()
        //设置背景
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: .highlighted)
        //设置图片
        button.setImage(UIImage(named:"tabbar_compose_icon_add"), for: .normal)
        button.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: .highlighted)
        //添加点击事件
        button.addTarget(self, action: #selector(composeDidClick), for: .touchUpInside)
        //添加到tabbar里面
        self.addSubview(button)
        
        return button
    }()
    // MARK: - 按钮点击事件
    func composeDidClick() -> Void {
        // UIView是Modal不出控制器，加号按钮的点击事件应该让HMMainTabBarController去处理
        // 使用闭包，谁调用闭包，谁准备闭包
        
        composeCallback?()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 宽度
        let width = self.frame.width / CGFloat(count)
        let height = self.frame.height
        
        var index = 0
        for subView in self.subviews{
            // 是这个类型：UITabBarButton,就修改位置
            if subView.isKind(of: NSClassFromString("UITabBarButton")!){
                // 修改frame ，给加号按钮腾出位置
                let x = CGFloat(index) * width
                let y:CGFloat = 0
                let newFrame = CGRect(x: x, y: y, width: width, height: height)
                subView.frame = newFrame
                
                index += 1
                // 给index=2空位置,留给加号按钮
                if index == 2 {
                    // 设置加号按钮的位置
                    composeButton.frame = CGRect(x: CGFloat(index) * width, y: 0, width: width, height: height)
                    
                    index += 1
                }
            }
            
        }
        
    }

}


